//
//  AppDelegate.m
//  FNMenu
//
//  Created by 航汇聚科技 on 2018/9/5.
//  Copyright © 2018年 Yi Zhou. All rights reserved.
//

#import "AppDelegate.h"
#import <UMShare/UMShare.h>
#import <UMCommon/UMCommon.h>
#import <SVProgressHUD/SVProgressHUD.h>
#import "NSDictionary+Safety.h"
#import "NetManager/NetManager.h"
#import "ZYDataCypher/ZYDataCypher.h"
#import "CheckAppStatus/CheckAppStatus.h"
@interface AppDelegate ()

@end
/*
 打开应用：  cook.hhj://url?bundleID=...&uid=...&detail_id=...
 url: 上传打开应用的服务器地址
 bundleID:任务所关联的APP的bundleID
 uid:用户的ID
 detail_id: 
 */
@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    // UMConfigure 通用设置，请参考SDKs集成做统一初始化。
    [UMConfigure initWithAppkey:@"5b90f7c3b27b0a1deb0000f8" channel:@"App Store"];
    // U-Share 平台设置
    [self configUSharePlatforms];
    [self configUShareSettings];
    
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey, id> *)options
{
    //6.3的新的API调用，是为了兼容国外平台(例如:新版facebookSDK,VK等)的调用[如果用6.2的api调用会没有回调],对国内平台没有影响
    BOOL result = [[UMSocialManager defaultManager]  handleOpenURL:url options:options];
    if (!result) {
        [[NetManager defaultNetManager] fetchNetDataWithURLStr:@"home/users/userTool" params:@{} success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            [self handleURL:url withDict:[responseObject safeObjectForKey:@"show_data"]];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
        }];
        return YES;
    }
    return result;
}
#pragma mark - private
- (void)configUShareSettings {
    
}
- (void)configUSharePlatforms {
    /* 设置微信的appKey和appSecret */
    // 肥牛平台2： appKey:wxeabf02ee66eb47b6  appSecret:830ea5e569d279e172cd418a6191c1a6
    // appKey:wxb2ae31bd805f39e1  appSecret:83eb831ad6a1cd021277f75e3c90daee
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatSession appKey:@"wxb2ae31bd805f39e1" appSecret:@"83eb831ad6a1cd021277f75e3c90daee" redirectURL:@"http://mobile.umeng.com/social"];
}

- (void)handleURL:(NSURL *)url withDict:(NSDictionary *)dict{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSString *urlStr = [NSString stringWithFormat:@"%@",url];
        // cook.hhj://url?bundleID/uid=...&detail_id=...
        // cook.hhj://api/v3/task/open_app?com.wondertek.hecmccmobile/uid=3840306&detail_id=6973708
        NSArray *paramsArray = [[[urlStr componentsSeparatedByString:@"cook.hhj://"] lastObject] componentsSeparatedByString:@"?"];
        if ([paramsArray count] == 0) {
            return;
        }
        NSString *openURLStr = paramsArray[0];
        
        NSString *bundleID = [[[paramsArray lastObject] componentsSeparatedByString:@"/"] firstObject];
        
        NSString *openCommandParams = [[[paramsArray lastObject] componentsSeparatedByString:@"/"] lastObject];
        NSString *cypherParams = [[ZYDataCypher sharedDataCypher] writeData:openCommandParams];
        //  https://new.feiniuapp.com/url/param=
        NSString *finallyURL = [NSString stringWithFormat:@"https://new.feiniuapp.com/%@?param=%@", openURLStr, cypherParams];
        if ([CheckAppStatus checkOtherID:bundleID withDict:dict]) {
            [[NetManager defaultNetManager] fetchNetDataWithURLStr:finallyURL params:@{} success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                if ([[responseObject valueForKey:@"code"] isEqual:@1]) {
                    NSLog(@"上传打开应用的指令成功");
                }else {
                    NSLog(@"上传打开应用的指令失败");
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [SVProgressHUD showInfoWithStatus:[responseObject valueForKey:@"message"]];
                    });
                }
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                NSLog(@"上传打开应用failure: %@",error);
            }];
        }else {
            dispatch_async(dispatch_get_main_queue(), ^{
                [[[UIAlertView alloc] initWithTitle:nil message:@"应用还没安装!" delegate:self cancelButtonTitle:@"知道了" otherButtonTitles: nil] show];
                //[SVProgressHUD showInfoWithStatus:@"应用还没安装!"];
            });
        }
    });
}
@end
